package com.haochang.chunkvod.controller.activity.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.database.order.GoodsInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.controller.adapter.order.ActiveExpandableAdapter;
import com.haochang.chunkvod.model.order.ActiveInfo;
import com.haochang.chunkvod.model.order.FoodDetailInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.query.GroupGoodsInfo;
import com.haochang.chunkvod.tools.vod.event.EventObserver;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.view.vod.ViewGroup.CustomFlowLayout;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

/**
 *@author qintao
 *created at 2016/6/17 18:27
 * 活动详情
 */

public class EventDetailsActivity extends BaseActivity implements EventObserver, CustomFlowLayout.OnSingleCheckedChangeListener_
{
	private TitleView titleView;
	private ExpandableListView ex_listView;
	private BaseTextView tv_foodName;
	private BaseTextView tv_price;
	private ImageView img_cart;
	private BaseTextView tv_estimate;
	private BaseTextView tv_give;
	private RelativeLayout lin_right;
	private BaseTextView tv_decTime;
	private BaseTextView tv_decValue;
	private BaseTextView tv_list_title;
	private CustomFlowLayout flowLayout;//商品关联组
	private LinearLayout groupActivies;
	private ActiveExpandableAdapter adapter;
	private List<ActiveInfo> activeInfoList = new ArrayList<ActiveInfo>();
	private List<GroupGoodsInfo> listPackage;//商品关联组list
	private OrderData orderData;
	private GoodsInfo goodInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		EventProxy.addEventListener(this, IEventConstant.ADD_SHOP_CART_SUCCESS);
	}

	@Override
	public void receiveParam()
	{
		goodInfo = (GoodsInfo) getIntent().getSerializableExtra(IntentKey.GOODSINFO);
		Logger.e(goodInfo.getCharging_room_type_id() + "KLJ");
	}

	@Override
	public void initData()
	{
		orderData = new OrderData(EventDetailsActivity.this);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_event_details);
		flowLayout = (CustomFlowLayout) findViewById(R.id.flowLayout);
		groupActivies = (LinearLayout) findViewById(R.id.groupActivies);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(String.format("%s", goodInfo.getGoodsName())).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
			}

			@Override
			public void onDoneClick()
			{
				{
					List<String> list = new ArrayList<String>();
					list.add("退出登录");
					int location[] = new int[2];
					ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
					img.getLocationOnScreen(location);
					int x = location[0];
					final VodPopWindow pop = new VodPopWindow(EventDetailsActivity.this, list);
					pop.showPopupWindow(titleView, x);
					pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
					{
						@Override
						public void onSelectItem(int position)
						{
							switch (position)
							{
							case 0:
								loginOut();
								break;
							default:
								break;
							}
						}
					});
				}
			}
		});
		tv_foodName = (BaseTextView) findViewById(R.id.tv_foodName);
		tv_price = (BaseTextView) findViewById(R.id.tv_price);
		img_cart = (ImageView) findViewById(R.id.img_cart);
		tv_estimate = (BaseTextView) findViewById(R.id.tv_estimate);
		tv_give = (BaseTextView) findViewById(R.id.tv_give);
		lin_right = (RelativeLayout) findViewById(R.id.lin_right);
		lin_right.setOnClickListener(mOnBaseClickListener);
		tv_decTime = (BaseTextView) findViewById(R.id.tv_dectime);
		tv_decValue = (BaseTextView) findViewById(R.id.tv_decvalue);
		ex_listView = (ExpandableListView) findViewById(R.id.ex_listView);
		tv_list_title = (BaseTextView) findViewById(R.id.tv_list_title);
		tv_foodName.setText(goodInfo.getGoodsName());
		tv_price.setText(String.valueOf(SaleUtils.getSaleString(goodInfo.getPrice()) + "/" + goodInfo.getUnit()));
		adapter = new ActiveExpandableAdapter(EventDetailsActivity.this, activeInfoList);
		ex_listView.setAdapter(adapter);
		requestActiveDetailFood(goodInfo.getGoodsId(), goodInfo.getRoomId());
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.lin_right:
				GoodsInfo info = GoodsInfoDao.getDao().queryBuilder(GoodsInfo.class, "bill_id", goodInfo.getBillId(), "goods_id", goodInfo.getGoodsId(),
						"goods_type", "2");
				if (null != info)
					ToastUtils.showText(EventDetailsActivity.this, "购物车已添加该活动，下单后可再次购买");
				else
					adapter.addToGoods(goodInfo);
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 初始化 商品关联组view
	 */
	private void initFlowLayout(List<GroupGoodsInfo> list)
	{
		if (!CollectionUtils.isEmpty(list))
		{
			flowLayout.removeAllViews();
			int length = list.size();
			View[] views = new View[length];
			if (length > 0)
			{
				int _5dp = DipPxConversion.dip2px(EventDetailsActivity.this, 5);
				for (int j = 0; j < length; j++)
				{
					LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					final ViewGroup viewGroup = null;
					RadioButton radioButton = (RadioButton) LayoutInflater.from(EventDetailsActivity.this).inflate(R.layout.inflate_flowlayot_order_package,
							viewGroup, false);
					params.setMargins(_5dp, _5dp, _5dp, _5dp);
					radioButton.setLayoutParams(params);
					radioButton.setText(list.get(j).getName());
					radioButton.setChecked(TextUtils.equals(goodInfo.getGoodsName(), list.get(j).getName()));
					views[j] = radioButton;
				}
				flowLayout.addData(views, true);
			}
		}
	}

	/**
	 * 获取点餐活动详情
	 * @param active_id 活动id
	 * @param roomId 房间id
	 */
	private void requestActiveDetailFood(String active_id, final String roomId)
	{
		orderData.requestActiveDetailFood(active_id, roomId, new OrderData.IOrderGoodDetailListener()
		{
			@Override
			public void onRequestSuccess(GoodsInfo info)
			{
				if (info != null)
				{
					info.setBillId(goodInfo.getBillId());
					info.setMenuId(goodInfo.getMenuId());
					info.setIs_give(goodInfo.is_give());
					info.setCharging_room_type_id(goodInfo.getCharging_room_type_id());
					goodInfo = info;
					titleView.setTitle(String.format("%s", goodInfo.getGoodsName()));
					tv_foodName.setText(goodInfo.getGoodsName());
					tv_price.setText(String.valueOf(SaleUtils.getSaleString(goodInfo.getPrice()) + "/" + goodInfo.getUnit()));
					if (info.is_give())
					{
						img_cart.setVisibility(View.GONE);
						tv_estimate.setVisibility(View.GONE);
						tv_give.setVisibility(View.VISIBLE);
					} else
					{
						img_cart.setVisibility(View.VISIBLE);
						tv_estimate.setVisibility(View.GONE);
						tv_give.setVisibility(View.GONE);
					}
					if (!CollectionUtils.isEmpty(info.getGroupGoodsInfoList()))
					{
						listPackage = info.getGroupGoodsInfoList();
						initFlowLayout(listPackage);
						groupActivies.setVisibility(View.VISIBLE);
					} else
						groupActivies.setVisibility(View.GONE);
					goodInfo.setDecrease_time(info.getDecrease_time());
					tv_decTime.setText(Html.fromHtml("减免" + "<font  color=#f04e39>" + info.getDecrease_time() + "分钟" + "</font>" + "房费"));
					tv_decValue.setText(SaleUtils.getSaleString(info.getDecrease_value()));
					try
					{
						activeInfoList.clear();
						JSONArray jsonArray = null;
						if (TextUtils.isEmpty(info.getGoodsDetial()))
							jsonArray = new JSONArray();
						else
							jsonArray = new JSONArray(info.getGoodsDetial());
						if (jsonArray.length() > 0)
						{
							for (int i = 0; i < jsonArray.length(); i++)
							{
								ActiveInfo activeInfo = new ActiveInfo(jsonArray.getJSONObject(i));
								activeInfoList.add(activeInfo);
							}
						}
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
					if (CollectionUtils.isEmpty(activeInfoList))
						tv_list_title.setVisibility(View.GONE);
					else
						tv_list_title.setVisibility(View.VISIBLE);
					adapter.setData(activeInfoList);
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && requestCode == IntentCode.ACTIVIE_REQUEST && resultCode == RESULT_OK)
		{
			FoodDetailInfo info = (FoodDetailInfo) data.getSerializableExtra(IntentKey.FOODINFO);
			if (info != null)
				adapter.activityForResultRefreshChildData(info);
			ActiveInfo activeInfo = (ActiveInfo) data.getSerializableExtra(IntentKey.ACTIVEINFO);
			if (activeInfo != null)
				adapter.activityForResultRefreshGroupData(activeInfo);
		}
	}

	@Override
	public void onNotify(Object sender, int eventId, Object... args)
	{
		switch (eventId)
		{
		case IEventConstant.ADD_SHOP_CART_SUCCESS:
			ToastUtils.showText(EventDetailsActivity.this, "添加成功");
			EventDetailsActivity.this.finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy()
	{
		EventProxy.removeEventListener(IEventConstant.ADD_SHOP_CART_SUCCESS, this);
		super.onDestroy();
	}

	@Override
	public void onSingleCheckedChanged_(int position, boolean b, CompoundButton compoundButton)
	{
		//选择套餐组之后的操作
		if (!CollectionUtils.isEmpty(listPackage))
		{
			requestActiveDetailFood(listPackage.get(position).getActiveId(), goodInfo.getRoomId());
		}
	}
}
